from http import HTTPStatus
from urllib.parse import quote
from ..base import Entity, Object
from lib.util.log import Log
from datetime import datetime
from lib.db import accessor

class Resource(Object):
    __slots__ = ('config', 'log', 'httpStatus', 'accessor')
    __RESPONSE_SUCCESS_FORMAT = '{"success":true,"total":%s,"list":%s,"params":%s}'
    __RESPONSE_FAILURE_FORMAT = '{"success":false,"error":"%s"}'

    @classmethod
    def setParams(cls, app_config):
        cls.log = Log
        Resource.config = app_config
        Resource.httpStatus = HTTPStatus
        Resource.accessor = accessor

    @classmethod
    def responseStatus(cls, status):
        return '%s %s' % (status.value, getattr(status, 'phrase'))
    @classmethod
    def response(cls, status=HTTPStatus.OK, data=[], total=0, params=()):
        if status == HTTPStatus.OK:
            r = cls.__RESPONSE_SUCCESS_FORMAT % (total, Entity.stringify(data), Entity.stringify(params))
        else:
            r = cls.__RESPONSE_FAILURE_FORMAT % (quote(data) if isinstance(data, str) and data else getattr(status, 'phrase'))
        
        return r.encode(), cls.responseStatus(status), {"Content-Type": "application/json", 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Method': '*', 'Access-Control-Allow-Headers': 'x-requested-with,content-type'}

    @classmethod
    def getUTCTime(self):
        return int(datetime.utcnow().timestamp())
